package org.abettor.pushbox.activity;

import java.io.File;
import java.io.IOException;

import org.abettor.pushbox.config.Config;
import org.abettor.pushbox.db.PushBoxDbHelper;
import org.abettor.pushbox.db.PushBoxMapBeanManage;
import org.abettor.pushbox.map.Boxmap;
import org.abettor.pushbox.map.BoxmapUtil;
import org.abettor.pushbox.upload.UploadMap;
import org.abettor.pushbox.upload.UploadMap.UpdateUploadMap;
import org.abettor.pushbox.util.FileUtil;
import org.abettor.pushbox.R;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

/**
 * 自做图库的推箱子操作
 * 
 * @author jzh
 * 
 */
public class SelfPushBoxActivity extends AbstractPushBoxActivity {
	@SuppressWarnings("unused")
	private final int NOT_UPLOADED = 0,UPLOADED = 1;//用来指示是否已经上传过
	private final int FULL_UNFULL_SCREEN_ID = Menu.FIRST;// 全屏
	private final int RESTART_GAME = Menu.FIRST + 1;// 重新开始
	private final int PRE_STEP = Menu.FIRST + 2;// 上一步的操作
	private final int SHOCK_UNSHOCK_ID = Menu.FIRST + 3;// 打开按键反馈
	private final int DEL_MAP = Menu.FIRST + 4;// 删除地图
	private final int UPLOAD_MAP_ID = Menu.FIRST + 5;//上传地图
	private int map_id = -1;// 地图的id
	private int is_uploaded = 0;//判断是否已经上传过
	private UploadMap uploadMapBean = null;
	PushBoxMapBeanManage manage = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		manage = new PushBoxMapBeanManage(this);
		super.onCreate(savedInstanceState);
		Intent intent = getIntent();
		Bundle extras = intent.getExtras();
		map_id = extras.getInt("_id");// 获得数据的id
		is_uploaded = manage.getUploadedStatus(map_id);
		uploadMapBean = new UploadMap(this);
	}

	// 读取地图文件
	private byte[] readFile(String mapFileName) throws IOException {
		String filepath = Config.getSelfBasePath() + File.separator
				+ mapFileName + ".map";
		return super.readFileByPath(filepath);
	}

	/**
	 * 创建系统菜单
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		boolean result = super.onCreateOptionsMenu(menu);
		if (m_pushConfig.getFullScreenOn() == 0) {// 是否打开全屏
			menu.add(0, FULL_UNFULL_SCREEN_ID, 0, R.string.full_screen)
					.setIcon(R.drawable.full_screen_on);
		} else {
			menu.add(0, FULL_UNFULL_SCREEN_ID, 0, R.string.un_full_screen)
					.setIcon(R.drawable.full_screen_off);
		}
		menu.add(0, RESTART_GAME, 1, R.string.restart_game).setIcon(
				R.drawable.reset);
		menu.add(0, PRE_STEP, 2, R.string.pre_step).setIcon(R.drawable.go_back);
		if (m_pushConfig.getShakeOn() == 0) {
			menu.add(0, SHOCK_UNSHOCK_ID, 3, R.string.shock_open).setIcon(
					R.drawable.shaken_on);
		} else {
			menu.add(0, SHOCK_UNSHOCK_ID, 3, R.string.shock_close).setIcon(
					R.drawable.shaken_off);
		}
		menu.add(4, DEL_MAP, 4, R.string.del_map).setIcon(R.drawable.remove);
		return result;
	}

	/**
	 * 系统菜单执行的操作
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case FULL_UNFULL_SCREEN_ID:// 全屏
			fullScreen();
			break;
		case RESTART_GAME:// 重新开始游戏
			restart();
			break;
		case PRE_STEP:// 上一步操作
			revert();
			break;
		case SHOCK_UNSHOCK_ID:// 打开按键反馈
			onShock();
			break;
		case DEL_MAP:// 删除地图的操作
			delMap();
			break;
		case UPLOAD_MAP_ID://上传地图的操作
			uploadMap(map_id);
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	//上传地图的操作
	public void uploadMap(final int id){
		String filename = manage.getFileName(id);
		// 读取图片的操作
		try {
			byte[] data = FileUtil.readFileByPath(Config.getSelfBasePath()
					+ File.separator + filename + ".map");
			UpdateUploadMap in = new UpdateUploadMap(){
				@Override
				public void update(int id) {
					manage.updateUploadStateSuccess(map_id, id);
					//重新读取状态
					is_uploaded = manage.getUploadedStatus(map_id);
				}
			};
			uploadMapBean.uploadMap(data, in);
		} catch (IOException e) {
		}
	}
	// 删除地图的操作
	public void delMap() {
		if (map_id == -1) {
			return;
		}
		String filename = manage.getFileName(map_id);
		manage.delPushBoxMapBean(map_id);
		deleteTheFile(filename);
		Toast.makeText(SelfPushBoxActivity.this, R.string.del_map_success,
				Toast.LENGTH_LONG).show();
		super.onBackPressed();
	}

	// 删除过期的不用的文件
	private void deleteTheFile(String filename) {
		try {
			File file = new File(Config.getSelfBasePath() + File.separator
					+ filename + ".map");
			if (file.exists()) {
				file.delete();
			}
			file = new File(Config.getSelfBasePath() + File.separator
					+ filename + ".thumb");
			if (file.exists()) {
				file.delete();
			}
			file = new File(Config.getSelfBasePath() + File.separator
					+ filename + ".draft");
			if (file.exists()) {
				file.delete();
			}
		} catch (Exception e) {
		}
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		MenuItem full = menu.findItem(FULL_UNFULL_SCREEN_ID);
		if (m_pushConfig.getFullScreenOn() == 0) {
			full.setIcon(R.drawable.full_screen_on);
			full.setTitle(R.string.full_screen);
		} else {
			full.setIcon(R.drawable.full_screen_off);
			full.setTitle(R.string.un_full_screen);
		}
		MenuItem shock = menu.findItem(SHOCK_UNSHOCK_ID);
		if (m_pushConfig.getShakeOn() == 0) {
			shock.setIcon(R.drawable.shaken_on);
			shock.setTitle(R.string.shock_open);
		} else {
			shock.setIcon(R.drawable.shaken_off);
			shock.setTitle(R.string.shock_close);
		}
		//来设置上传的按钮
		if(is_uploaded != UPLOADED){
			MenuItem uploaded = menu.findItem(UPLOAD_MAP_ID);
			if(uploaded == null){//没有这个选项向menu中加入这个菜单
				menu.add(0, UPLOAD_MAP_ID, 6, R.string.upload_map).setIcon(
						R.drawable.upload);
			}
		}else{
			MenuItem uploaded = menu.findItem(UPLOAD_MAP_ID);
			if(uploaded != null){//上传后还有这个选项，把它从列表中删除掉
				menu.removeItem(UPLOAD_MAP_ID);
			}
		}
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	protected Boxmap initTheBoxMap() {
		Intent intent = getIntent();
		Bundle extras = intent.getExtras();
		map_id = extras.getInt("_id");// 获得数据的id
		PushBoxDbHelper helper = new PushBoxDbHelper(this);
		SQLiteDatabase base = helper.getWritableDatabase();
		Cursor c = base.query(PushBoxDbHelper.PUSH_BOX_TABLE_NAME,
				new String[] { PushBoxDbHelper.PUSH_BOX_NAME },
				PushBoxDbHelper.PUSH_BOX_ID + "=" + map_id, null, null, null,
				null);
		if (c.moveToFirst()) {
			int index = c.getColumnIndex(PushBoxDbHelper.PUSH_BOX_NAME);
			String name = c.getString(index);// 获得名字
			byte[] buf = null;
			try {
				buf = readFile(name);
			} catch (IOException e) {
			}
			m_map = BoxmapUtil.paraArrayToMap(buf);// 生成地图
		}
		c.close();
		base.close();
		return m_map;
	}

	@Override
	protected void successOperation() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		AlertDialog dialog = builder.create();
		dialog.setTitle(R.string.mod_private_map);
		dialog.setMessage(this.getText(R.string.push_map_success));
		dialog.setButton(DialogInterface.BUTTON_NEGATIVE, this
				.getText(android.R.string.ok),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						updateState();
						SelfPushBoxActivity.this.onBackPressed();
					}
				});
		dialog.show();
	}
	//更新地图的状态
	private void updateState(){
		manage.updatePushBoxMapBeanSuccess(map_id);
	}
	@Override
	protected String getStepFileName() {
		String filename = manage.getFileName(map_id);
		String filepath = Config.getSelfBasePath() + File.separator + filename
				+ ".step";
		return filepath;
	}
}
